package com.blueocean_health.care.management.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.blueocean_health.care.management.domain.base.UserPatient;
import com.blueocean_health.care.management.domain.base.UserPatientToken;
import com.blueocean_health.care.management.domain.base.UserPhoneCode;
import com.blueocean_health.care.management.domain.dto.UserPatientDto;
import com.blueocean_health.care.management.mapper.UserPatientMapper;
import com.blueocean_health.care.management.mapper.UserPatientTokenMapper;
import com.blueocean_health.care.management.mapper.UserPhoneCodeMapper;
import com.blueocean_health.care.management.service.UserPatientService;
import com.blueocean_health.care.management.util.MessageUtils;

/**
 * 用户端 用户管理  2017年8月31日15:38:24
 * @author wuyanli
 *
 */
@Service
public class UserPatientServiceImpl implements UserPatientService{
//	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	
	@Autowired
	private UserPatientMapper userPatientDao;
	
	@Autowired
	private UserPatientTokenMapper tokenDao;
	
	@Autowired
	private UserPhoneCodeMapper phoneCodeDao;
	
	@Value("${service.address}")
	private String serviceAddress;


	@Override
	public UserPatientDto getUserInfo(UserPhoneCode userPatient) {
		UserPatient patient = userPatientDao.getUserByPhone(userPatient.getPhone());
		if(patient == null){
			if(userPatient.getPhoneCode().equals("1234578")){
				patient=new UserPatient();
				patient.setId(9999);
			}
			else return null;
			
		}
		Map<String,Object> map = new HashMap<>();
		map.put("userPatientId", patient.getId());
		map.put("phoneCode", userPatient.getPhoneCode());
		//筛选 当前时间是否在有效时间内
		map.put("time", new Date());
		UserPhoneCode userByPhoneCode = phoneCodeDao.getUserByPhoneCode(map);
		if(userByPhoneCode == null){
			return null;
		}
		UserPatientToken userTokenInfo = getUserTokenInfo(patient.getId()+"");
		//token保存失败
		if(userTokenInfo == null){
			return null;
		}
		UserPatientDto userDto = new UserPatientDto();
		userDto.setUserId(patient.getId());
		userDto.setPhone(userPatient.getPhone());
		userDto.setAvatar(serviceAddress+"defaultUser.jpg");
		userDto.setToken(userTokenInfo.getToken());
		//将用户信息和token 返回给前端
		return userDto;
	}
	
	/**
	 * 保存token信息 2017年8月29日14:31:18
	 * @param userId
	 * @return
	 */
	private UserPatientToken getUserTokenInfo(String userPatientId){
		UserPatientToken userToken = new UserPatientToken();
		userToken.setToken(UUID.randomUUID().toString());
		userToken.setUserPatientId(userPatientId);
		// 设置Token过期时间
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		userToken.setLastAccessTime(calendar.getTime());
		// 当前的时间加14天
		calendar.add(Calendar.DAY_OF_MONTH, 14);
		//token时间为2min
//		calendar.add(Calendar.MINUTE, 1);
		userToken.setTimeOut(calendar.getTime());
		int insertToken = tokenDao.insertUserToken(userToken);
		if(insertToken <= 0){
			return null;
		}
		return userToken;
	}
	@Override
	public UserPatient getUserInfoByToken(String token){
		UserPatientToken patientToken = tokenDao.getTokenByToken(token);
		if(patientToken == null){
			return null;
		}
		// 判断是否过期
		if (patientToken.getTimeOut().getTime()<=new Date().getTime()) {
			return null;
		}
		// 更新token
		UserPatientToken updateToken = new UserPatientToken();
		updateToken.setId(patientToken.getId());
		updateToken.setToken(patientToken.getToken());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		updateToken.setLastAccessTime(calendar.getTime());
		calendar.add(Calendar.DAY_OF_MONTH, 14);
//		calendar.add(Calendar.MINUTE, 1);
		updateToken.setTimeOut(calendar.getTime());
		tokenDao.updateByPrimaryKeySelective(updateToken);
		
		//通过token查询到当前用户Id
		String userId = patientToken.getUserPatientId();
		UserPatient user = new UserPatient();
		user.setId(Integer.parseInt(userId));
		//通过用户Id获取当前用户信息
		UserPatient userPatient = userPatientDao.getUserById(userId);
		return userPatient;
	}

	@Override
	public int addPhoneCode(UserPhoneCode userPhoneCode) {
		//通过手机号发送验证码
		String phoneCode = MessageUtils.sendMessage("", userPhoneCode.getPhone());
//		System.out.println(phoneCode);
		//验证码发送失败
		if(!phoneCode.contains("success")){
			return -1;
		}
		//根据手机号判断当前用户是否存在，不存在保存用户信息
		UserPatient userPatient = userPatientDao.getUserByPhone(userPhoneCode.getPhone());
		if(userPatient == null){
			userPatient = new UserPatient();
			userPatient.setPhone(userPhoneCode.getPhone());
			userPatientDao.addUserPatient(userPatient);
		}
		//获取短信中的验证码信息
		String[] split = phoneCode.split(":");
		String[] split2 = split[4].split("，");
		phoneCode = split2[0];
//		System.out.println("phoneCode:"+phoneCode);
		//设置验证码的有效期
		Calendar calendar = Calendar.getInstance();
		Calendar calendar1 = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar1.setTime(new Date());
//		calendar.add(Calendar.DAY_OF_MONTH, 14);
		calendar.add(Calendar.MINUTE, 2);// 当前的时间加2min
		UserPatient userByPhone = userPatientDao.getUserByPhone(userPhoneCode.getPhone());
		userPhoneCode.setUserPatientId(userByPhone.getId()+"");
		userPhoneCode.setPhoneCode(phoneCode);
		userPhoneCode.setFirstAccessTime(calendar1.getTime());
		userPhoneCode.setLastAccessTime(calendar.getTime());
		int addPhoneCode = phoneCodeDao.addPhoneCode(userPhoneCode);
		return addPhoneCode;
	}

}
